import { ref } from 'vue'

// type CallbackFn = (item?: any) => void

export function usePageDialogForm(formData: any[]) {
  const dialogVisible = ref(false)
  const newFormItem = ref({})
  const updateFlag = ref(false)
  const oldFormItem = ref({ name: '' })

  const openDialog = (item: any) => {
    dialogVisible.value = true
    if (!item?.target) {
      oldFormItem.value = JSON.parse(JSON.stringify(item))
      newFormItem.value = JSON.parse(JSON.stringify(item))
      updateFlag.value = true
    }
  }
  const closeDialog = () => {
    dialogVisible.value = false
  }

  const handleConfirm = () => {
    dialogVisible.value = false
    if (!updateFlag.value) {
      formData.push(newFormItem.value)
    } else {
      const index = formData.findIndex(
        (item) => item.name === oldFormItem.value.name
      )
      if (index !== -1) {
        formData.splice(index, 1, newFormItem.value)
      }
    }
    updateFlag.value = false
    newFormItem.value = {}
  }

  return { dialogVisible, newFormItem, openDialog, closeDialog, handleConfirm }
}
